<?php
class Goods extends BZ_Controller
{
    public $specArray;
    public $attribute;

    public function _init()
    {
        $this->load->library('pagination');
        $this->load->helper('common');
        $this->load->model('region_model', 'region');
        $this->load->model('tourism_goods_base_model', 'tourism_goods_base');
        $this->load->model('tourism_goods_attr_model', 'tourism_goods_attr');
        $this->load->model('tourism_goods_category_spec_model', 'tourism_goods_category_spec');
        $this->load->model('tourism_goods_brand_model', 'tourism_goods_brand');
        $this->load->model('tourism_order_reviews_model', 'tourism_order_reviews');
        $this->load->model('tourism_enshrine_model', 'tourism_enshrine');
        $this->load->model('tourism_goods_category_model', 'tourism_goods_category');
        $this->load->model('tourism_order_model', 'tourism_order');
        $this->load->model('tourism_provider_model','tourism_provider');
        $this->load->model('tourism_collect_shop_model','tourism_collect_shop');
        $this->load->model('tourism_freight_free_model', 'tourism_freight_free');
        $this->load->model('tourism_freight_template_model','tourism_freight_template');
        $this->load->model('tourism_freight_price_list_model','tourism_freight_price_list');
    }
    
    public function search()
    {
        $keyword = trim(addslashes($this->input->get('keyword')));
        /*搜索历史记录*/
        if ( !empty($keyword) ) {
            seeHistory($keyword, $type=2);
        }
        $cid = $this->input->get('cid');
        $data['category'] = $this->tourism_goods_category->find(array('level' => 1));
        $ids = empty($cid) ? array() :  $this->tourism_goods_category->getCategoryChildrenIds($cid);
        $list = $this->tourism_goods_base->search($pgNum=20, $num=0, $this->input->get(),$ids);
        $data['more'] = ($list->num_rows() > 0) ? (($list->num_rows() >= 20) ? true : false) : false;
        $data['cid'] = $cid;
        $data['list'] = $list;
        $data['keword'] = $keyword;
        $this->load->view('tourism/goods/search', $data);
    }

     /**
     *显示下级元素
     */
    public function ajaxCategory()
    {
        $cid = $this->input->post('cid');
        $level = $this->input->post('level');
        $parent_id = $this->input->post('parent_id');
        $find = $this->input->post('find');
        $category = empty($cid) ? $this->tourism_goods_category->findPrevCategory($level, $parent_id) : $this->tourism_goods_category->findChildren($cid);
        if ($find == 2) {
            $level = 1;
            $parent_id =  $this->tourism_goods_category->findById($parent_id)->row(0)->parent_id;
        }
        $data['cid'] = $cid;
        $data['find'] = $find ? $find : '2';
        $data['level'] = $level;
        $data['parent_id'] =  $parent_id;
        $data['category'] = $category;
        echo $category->num_rows() > 0 ?
        json_encode(array(
            'status' => true,
            'html'   => $this->load->view('tourism/goods/ajaxcategory', $data, true)
        )):json_encode(array(
            'status' => false,
        ));exit;
    }
    
     /**
     * 加载更多
     */
    public function ajaxSearch()
    {
        $pgNum = 20;
        $pg = $this->input->get('pg') ? $this->input->get('pg') : 2;
        $num = ($pg-1)*$pgNum;
        $cid = $this->input->get('cid');
        $getData = $this->input->get();
        $ids = empty($cid) ? array() : $this->tourism_goods_category->getCategoryChildrenIds($cid);
        $data['list'] = $this->tourism_goods_base->search($pgNum, $num, $getData, $ids);
        echo ($data['list']->num_rows() > 0) ? json_encode([
            'status' => true,
            'pg'     => $pg,
            'num'    => $data['list']->num_rows(),
            'html'   => $this->load->view('tourism/goods/list', $data, true)
        ]) : json_encode(['status' => false]);
        exit;
    }

    /**
     * 旅游商品详情页面
     * @param $goodsAttrId
     */
    public function info($goodsAttrId)
    {
        $result = $this->tourism_goods_base->findByGoodsAttrId($goodsAttrId);
        if ($result->num_rows() <= 0) {
            $this->redirect('tourism/tourism/error404');
        }
        $info = $result->row(0);
        $this->tourism_goods_attr->setTourismCount($goodsAttrId);
        //商品属性
        if (!empty($info->attribute_key)) {
            $attributeKey = explode(',', trim($info->attribute_key, ','));
            $categorySpec = $this->tourism_goods_category_spec->findBySpec($attributeKey);
            $this->data['categorySpec'] = $this->encrypt($categorySpec);
        }
        
        //限购数量
        if ($info->limit_num > 0 && $this->uid && $info->limit_day > 0) {
            $this->data['bayNum'] = $this->tourism_order->findBayNum($this->uid, $goodsAttrId, $info->limit_day);
        }

        //评价内容
        $this->data['info'] = $info;
        $this->data['reviewTotal'] = $this->tourism_order_reviews->total($goodsAttrId);

        $this->data['shop'] = $this->tourism_provider->findOne(['uid' => $info->uid]);

        $this->data['region'] = $this->region->findByType($parent_id = 1, $region_type = 1);
        $this->data['isExist'] = $this->tourism_enshrine->findIsExist($goodsAttrId, $this->uid);
        $this->data['headTitle'] = $info->goods_name;
        $this->load->view('tourism/goods/info', $this->data);
    }

    /**
     * 对商品属性的处理
     * @param $categorySpec
     * @return array
     */
    public function encrypt($categorySpec)
    {
        $resultSpec = array();
        if ($categorySpec->num_rows() > 0) {
            foreach ($categorySpec->result() as $item) {
                $resultSpec[$item->attr_id]['attr_name'] = $item->attr_name;
                $resultSpec[$item->attr_id]['attr_id']   = $item->attr_id;
                $resultSpec[$item->attr_id]['spec'][]    = $item;
            }
        }
        return $resultSpec;
    }

    /**
     * 预览 旅游商品详情页面
     * @param $goodsAttrId
     */
    public function preview($goodsAttrId)
    {
        $result = $this->tourism_goods_base->findByGoodsAttrIdPre($goodsAttrId);
        if ($result->num_rows() <= 0) {
            $this->redirect('tourism/tourism/error404');
        }
        $info = $result->row(0);
        //商品属性
        if (!empty($info->attribute_key)) {
            $attributeKey = explode(',', trim($info->attribute_key, ','));
            $this->data['categorySpec'] = $this->tourism_goods_category_spec->findBySpec($attributeKey);
        }

        //限购数量
        if ($info->limit_num > 0 && $this->uid && $info->limit_day>0) {
            $this->data['bayNum'] = $this->tourism_order->findBayNum($this->uid, $goodsAttrId, $info->limit_day);
        }

        //评价内容
        $this->data['info'] = $info;
        $this->data['reviewTotal'] = $this->tourism_order_reviews->total($goodsAttrId);

        $this->data['shop'] = $this->tourism_provider->providerInforByUid($info->uid);

        $this->data['region'] = $this->region->findByType($parent_id = 1,$region_type = 1);
        $this->data['isExist'] = $this->tourism_enshrine->findIsExist($goodsAttrId, $this->uid);
        $this->data['headTitle'] = $info->goods_name;
        $this->load->view('tourism/goods/preview', $this->data);
    }

    /**
     * 刚开始评论载入
     */
    public function reviews()
    {
        $goodsAttrId = $this->input->get('goodsAttrId');
        $flag = $this->input->get('flag');
        $result = $this->tourism_goods_base->isExistProduct($goodsAttrId);
        if ($result <= 0) {
            $this->redirect('tourism/tourism/error404');
        }
        $data['flag'] = $flag;
        $data['goodsAttrId'] = $goodsAttrId;
        $data['reviewTotal'] = $this->tourism_order_reviews->total($goodsAttrId);
        $data['total'] = $this->tourism_order_reviews->totalStatus($goodsAttrId, $flag);
        $data['review'] = $this->tourism_order_reviews->page_list($pgNum = 15, $num = 0, $goodsAttrId, $flag);
        $this->load->view('tourism/goods/reviews', $data);
    }

    /**
     * 评论载入的ajax刷新
     */
    function ajaxReview()
    {
        $pgNum = 15;
        $pg = $this->input->get('pg') ? $this->input->get('pg'):1;
        $num = ($pg-1)*$pgNum;
        $goodsAttrId = $this->input->get('goodsAttrId');
        $flag = $this->input->get('flag');
        $review = $this->tourism_order_reviews->page_list($pgNum,$num,$goodsAttrId,$flag);
        $data['review'] = $review;
        echo ($review->num_rows() > 0) ? json_encode([
            'status' => true,
            'pg'     => $pg,
            'num'    => $review->num_rows(),
            'html'   => $this->load->view('tourism/goods/ajaxreview', $data, true)
        ]) : json_encode([
            'status' => false,
        ]);exit;
    }

    /**
     * --加载推荐
     */
    public function ajaxRecommend()
    {
        $pgNum = 3;
        $pg = $this->input->post('pg') ? $this->input->post('pg') : 1;
        $num = ($pg-1)*$pgNum;
        $uid = $this->input->post('uid');
        $shopRecommend = $this->tourism_goods_base->findRecommend($pgNum,$num,$uid);
        if ($shopRecommend->num_rows() <= 0) {
            $pg = 1;
            $shopRecommend = $this->tourism_goods_base->findRecommend($pgNum,0,$uid);
        }
        $data['shopRecommend'] = $shopRecommend;
        echo json_encode([
           'status' => true,
           'pg'     => $pg,
           'html'   => $this->load->view('tourism/goods/recommend', $data, true)
        ]);exit;
    }

    /**
     * ajax刷运费
     */
    public function ajaxGetFreightPrice()
    {
        $param = $this->input->post();
        if ($param['transport_id'] == 0) {
            $this->jsonFreight(true,number_format($param['transport_cost'],2));
        }
        $params['id'] = $param['transport_id'];
        $params['uid'] = $param['uid'];
        $result = $this->tourism_freight_template->getTransports($params);
        $freeResult = $this->tourism_freight_free->getFreeByArea($param['transport_id'],$param['provice']);
        $freeArray = ($freeResult->num_rows() > 0) ? $freeResult->row(0) : array();
        
        if (isset($result->methods)) {
            $par['id'] = $param['transport_id'];
            $par['area'] = $param['provice'];
            $transport = $this->tourism_freight_price_list->getFreightRow($par);
            if ($result->methods == 1) {    //按件计算
                if ($transport->add_unit == 0) {  //如果没有增加的单位为零，直接为第一份的价格
                    $this->jsonFreight(true,number_format($transport->first_price,2));
                } else {
                    if (!empty($freeArray)) { // 如果有优惠信息
                        if (($freeArray->free_type==1) && (bcsub($param['qty'], $freeArray->number) >= 0)) { // 件数优惠
                            $this->jsonFreight(true,0);
                        }
                        if (($freeArray->free_type==2) && (bcsub(bcmul($param['qty'],$param['price'],2),$freeArray->money,2)>=0) ){ // 金额优惠
                            $this->jsonFreight(true,0);
                        }
                    }
                    if ($param['qty'] <= $transport->first_unit) {
                        $this->jsonFreight(true,number_format($transport->first_price,2));
                    } else {
                        $over_unit = $param['qty'] - $transport->first_unit;//计算超出部分
                        $over_price = ceil($over_unit / $transport->add_unit) * $transport->add_price;//超出部分价格
                        $this->jsonFreight(true,number_format($over_price + $transport->first_price,2));
                    }
                }
            }
            if ($result->methods == 2) { //按重量计算
                $total_weight = bcmul($param['weight']/1000,$param['qty'],3);
                if (!empty($freeArray)) { //如果有优惠信息
                    if (($freeArray->free_type == 1) && (bcsub($total_weight, $freeArray->number,3)>=0 )){ // 重量优惠
                        $this->jsonFreight(true,0);
                    }
                    if (($freeArray->free_type == 2) && (bcsub(bcmul($param['qty'], $param['price'],2), $freeArray->money,2) >= 0)){ // 金额优惠
                        $this->jsonFreight(true,0);
                    }
                }
                if ($transport->add_unit == 0) {  // 如果没有增加的单位为零，直接为第一份的价格
                    $this->jsonFreight(true,number_format($transport->first_price,2));
                } else{
                    if (bcsub($transport->first_unit,$total_weight,3)>=0) {
                        $this->jsonFreight(true,number_format($transport->first_price,2));
                    } else { //重量大于首重
                        $over_weight = bcsub($total_weight, $transport->first_unit,3);//计算超出部分
                        $over_price = ceil($over_weight / $transport->add_unit) * $transport->add_price;
                        $this->jsonFreight(true, number_format($over_price + $transport->first_price,2));
                    }
                }
            }
        }
    }
    
    /**
     * 运费 json 输出
     * @param unknown $flag
     * @param unknown $cost
     */
    public function jsonFreight($flag, $cost)
    {
        echo json_encode([
            'status' => $flag,
            'cost'   => $cost
        ]);exit;
    }
}